package xian.woniuxy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import xian.woniuxy.domain.ResultVo;
import xian.woniuxy.entity.Role;
import xian.woniuxy.service.RoleService;
import xian.woniuxy.service.RoleService;
import xian.woniuxy.service.impl.RoleServiceImpl;

import java.util.List;
import java.util.Map;

/**
 * @author gao
 * @date 2023/07/03 11:31:58
 */
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping("role/save")
    public ResultVo save(@RequestBody Role role) {
        int rows = roleService.save(role);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @PostMapping("role/update")
    public ResultVo update(@RequestBody Role role) {
        int rows = roleService.update(role);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @PostMapping("role/findAll")
    public ResultVo findAll() {
        List<Role> list = roleService.findAll();
        return ResultVo.success(list);
    }

    @PostMapping("role/findOne")
    public ResultVo findOne(@RequestBody String rid) {
        if (!StringUtils.hasText(rid)) {
            throw new RuntimeException("rid in blank");
        }
        Role role = roleService.findOne(Integer.valueOf(rid));
        return ResultVo.success(role);
    }

    @PostMapping("role/delete")
    public ResultVo delete(@RequestBody String roleId) {
        if (!StringUtils.hasText(roleId)) {
            throw new RuntimeException("roleId is null");
        }
        int rows = roleService.delete(Integer.valueOf(roleId));
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @PostMapping("role/distributePermission")
    public ResultVo distributePermission(@RequestBody Map map) {
        Integer roleId = (Integer) map.get("roleId");
        List<Integer> permissionIds = (List<Integer>) map.get("permissionIds");

        int rows = roleService.distributePermissions(roleId, permissionIds);

        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }
}
